package com.wgchao.authmanager.infrastructure.repository;

import com.wgchao.authmanager.domain.model.Role;
import com.wgchao.authmanager.domain.model.RoleIdentity;
import com.wgchao.authmanager.domain.repository.RoleRepository;
import com.wgchao.authmanager.infrastructure.convert.em.RoleInfoConvert;
import com.wgchao.authmanager.infrastructure.exception.IdNotExistException;
import com.wgchao.authmanager.infrastructure.exception.IdentifyUsedException;
import com.wgchao.authmanager.infrastructure.jpa.entity.AgencyInfo;
import com.wgchao.authmanager.infrastructure.jpa.entity.RoleInfo;
import com.wgchao.authmanager.infrastructure.jpa.repository.AgencyInfoJpaRepository;
import com.wgchao.authmanager.infrastructure.jpa.repository.RoleInfoJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName: RoleRepositoryImpl
 * @author: wgchao
 * @createTime: 2020/5/7 3:16 PM
 * @Description: TODO
 */
@Component
public class RoleRepositoryImpl implements RoleRepository {
    @Autowired
    private RoleInfoConvert roleInfoConvert;
    @Autowired
    private RoleInfoJpaRepository roleInfoJpaRepository;
    @Autowired
    private AgencyInfoJpaRepository agencyInfoJpaRepository;

    @Override
    public void add(Role role) {
        if(role.findId() == null || role.findId().compareTo(0L) <= 0){
            RoleInfo roleInfo = roleInfoJpaRepository.
                    findFirstByAgencyCodeAndRoleName(role.getIdentity().getAgencyCode(), role.getIdentity().getRoleName());
            if(roleInfo != null){
                throw new IdentifyUsedException("机构中已存在该角色");
            }
        }
        RoleInfo roleInfo = roleInfoConvert.toEntity(role);
        roleInfo.setDel(false);
        roleInfo = roleInfoJpaRepository.save(roleInfo);
    }

    @Override
    public void remove(Role role, String operator) {
        RoleInfo roleInfo = roleInfoConvert.toEntity(role);
        if(roleInfo.getId() == null){
            throw new IdNotExistException("主键缺失");
        }
        roleInfo.setDel(true);
        roleInfo.setLastUpdateUser(operator);
        roleInfo.setLastUpdateTime(new Date());
        roleInfo = roleInfoJpaRepository.save(roleInfo);
    }

    @Override
    public Role get(RoleIdentity id) {
        RoleInfo roleInfo = roleInfoJpaRepository.
                findFirstByAgencyCodeAndRoleNameAndDelIsFalse(id.getAgencyCode(), id.getRoleName());
        if(roleInfo == null){
            return null;
        }
        AgencyInfo agencyInfo = agencyInfoJpaRepository.findFirstByAgencyCodeAndDelFalse(roleInfo.getAgencyCode());
        if(agencyInfo == null || agencyInfo.isDisabled()){
            return null;
        }
        return roleInfoConvert.toModel(roleInfo);
    }
}
